package com.qfedu.springmvc02.service.impl;

import com.qfedu.springmvc02.dao.UserMapper;
import com.qfedu.springmvc02.entity.User;
import com.qfedu.springmvc02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public User selectOne(Integer id){
        return userMapper.selectOne(id);
    }

    @Override
    public int add(User user) {
        return userMapper.add(user);
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public int delete(Integer id) {
        return userMapper.delete(id);
    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public User login(String name, String password) {
        List<User> login = userMapper.login(name);
        if (Objects.nonNull(login)){
            for (User user : login) {
                if (Objects.equals(user.getPassword(),password)){
                    return user;
                }
            }
        }
        return null;
    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public List<User> selectByNameFuzzy(String name) {
        return userMapper.selectByNameFuzzy(name);
    }
}
